const tencentcloud = require('tencentcloud-sdk-nodejs-vpc')
const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml') // 引入js-yaml库

// 获取当前脚本所在目录的上级目录
const parentDir = path.dirname(__dirname)
const configFilePath = path.join(parentDir, 'local_config.yaml')

// 读取YAML配置文件
const configData = fs.readFileSync(configFilePath, 'utf8')
const config = yaml.safeLoad(configData) // 使用js-yaml的safeLoad方法解析YAML字符串

// 获取当前脚本所在目录的上级目录
const VpcClient = tencentcloud.vpc.v20170312.Client

const clientConfig = {
  credential: {
    secretId: config.tencentcloud.secretId,
    secretKey: config.tencentcloud.secretKey,
  },
  region: config.tencentcloud.region,
  profile: {
    httpProfile: {
      endpoint: config.tencentcloud.endpoint,
    },
  },
}

const createTencentPortTransport = (publicPort, node) => {
  const privateAddress =
    node === 'node1'
      ? config.network.nodeAddresses.node1
      : config.network.nodeAddresses.node2
  const params = {
    NatGatewayId: config.network.natGatewayId,
    DestinationIpPortTranslationNatRules: [
      {
        IpProtocol: 'TCP',
        PublicIpAddress: config.network.publicIpAddress,
        PublicPort: publicPort, // 使用传入的publicPort参数值
        PrivateIpAddress: privateAddress, // 使用传入的privateAddress参数值
        PrivatePort: publicPort,
        Description: 'Dev-container专用端口',
      },
    ],
  }
  const client = new VpcClient(clientConfig)
  return client.CreateNatGatewayDestinationIpPortTranslationNatRule(params)
}

const deleteTencentPortTransport = (publicPort, node) => {
  const privateAddress =
    node === 'node1'
      ? config.network.nodeAddresses.node1
      : config.network.nodeAddresses.node2
  const params = {
    NatGatewayId: config.network.natGatewayId,
    DestinationIpPortTranslationNatRules: [
      {
        IpProtocol: 'TCP',
        PublicIpAddress: config.network.publicIpAddress,
        PublicPort: publicPort, // 使用传入的publicPort参数值
        PrivateIpAddress: privateAddress, // 使用传入的privateAddress参数值
        PrivatePort: publicPort,
        Description: 'Dev-container专用端口',
      },
    ],
  }
  const client = new VpcClient(clientConfig)
  return client.DeleteNatGatewayDestinationIpPortTranslationNatRule(params)
}

module.exports = {
  createTencentPortTransport,
  deleteTencentPortTransport,
}
